<template>
  <div class="page-container">
    <!--表格内容栏-->
    <ac-table
      ref="dataTable"
      pkName="id"
      :filters="filters"
      :filterFields="filterFields"
      :columns="columns"
      @handleTableOperator="handleTableOperator"
      @handleCellOperator="handleCellOperator"
    />

    <!--新增/编辑/查看界面-->
    <el-dialog
      width="650px"
      v-model="dialogVisible"
      :title="dialogTitle"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <el-form
        :model="formData"
        ref="dataForm"
        label-width="120px"
        label-position="right"
        :disabled="!dialogEdit"
        :rules="rules"
        :hide-required-asterisk="!dialogEdit"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="名称" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="应用标识" prop="appKey">
              <el-input v-model="formData.appKey"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="应用密钥" prop="appSecret">
              <el-input v-model="formData.appSecret"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="Token有效期" prop="tokenTime">
              <ac-select
                v-model="formData.tokenTime"
                :options="tokenTimeOptions"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="24">
            <el-form-item label="Token获取地址" prop="url">
              <ac-input v-model="formData.url" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input v-model="formData.description" type="textarea" :rows="5" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="24">
            <el-form-item label="更新时间" prop="updateTime">
              <ac-datetime v-model="formData.updateTime" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="24">
            <el-form-item label="创建时间" prop="createTime">
              <ac-datetime v-model="formData.createTime" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible=false"
        >取消</el-button>
        <el-button
          v-if="dialogEdit"
          size="default"
          :type="formData.id ? 'warning' : 'success'"
          @click="resetToken"
          :loading="editLoading"
        >{{formData.id ? '重置密钥' : '生成密钥'}}</el-button>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
        <el-button
          v-if="!dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible=false"
        >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/http/api';
import tool from "@/utils/tool";

const filters = ref({
  name: ''
});

const filterFields = ref([
  {prop: "name", label: "名称"}
]);

const columns = ref([
  {prop: "name", label: "名称", minWidth: 160, click: true},
  {prop: "url", label: "Token获取地址", width: 280,
    formatter: () => {
      return tool.getBaseUrl() + '/v1/token';
    }
  },
  {prop: "tokenTime", label: "Token有效期", width: 130, formatter: (prop, value) => {
      if (value) {
        const option = tokenTimeOptions.value.find(item => item.key === value + '');
        if (option) return option.value;
      }
      return '';
    }
  },
  {prop: "description", label: "描述", minWidth: 100},
  {prop: "updateTime", label: "更新时间", width: 160, type: "datetime"},
  {prop: "createTime", label: "创建时间", width: 160, type: "datetime"},
]);

const rules = ref({
  name: [
    {required: true, message: '请输入名称', trigger: 'change'},
    {max: 100, message: '长度必须小于等于 100 个字符！', trigger: 'change'}
  ],
  appKey: [
    {required: true, message: '请输入标识', trigger: 'change'},
    {max: 36, message: '长度必须小于等于 36 个字符！', trigger: 'change'}
  ],
  appSecret: [
    {required: true, message: '请输入密钥', trigger: 'change'},
    {max: 36, message: '长度必须小于等于 36 个字符！', trigger: 'change'}
  ],
  tokenTime: [
    {required: true, message: '请输入Token有效期', trigger: 'change'}
  ],
  description: [
    {max: 4000, message: '长度必须小于等于 4000 个字符！', trigger: 'change'}
  ],
});

const dataTable = ref();
const dataForm = ref();
const formData = ref({});
const dialogTitle = ref('');
const dialogVisible = ref(false);
const editLoading = ref(false);
const dialogEdit = ref(false);
const tokenTimeOptions = ref([
  {key: '3600', value: '1小时'},
  {key: '18000', value: '5小时'},
  {key: '43200', value: '12小时'},
  {key: '86400', value: '1天'},
  {key: '172800', value: '2天'},
]);

const handleCellOperator = (property, value, row) => {
  row.tokenTime = row.tokenTime + '';
  formData.value = Object.assign({}, row);
  formData.value.url = tool.getBaseUrl() + '/v1/token';
  dialogVisible.value = true;
  dialogEdit.value = false;
  dialogTitle.value = "查看";

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const handleTableOperator = (button, row) => {
  row.tokenTime = (row.tokenTime || '') + '';
  dialogVisible.value = true;
  dialogEdit.value = true;
  dialogTitle.value = "编辑";

  if (button.buttonType === 'edit') {
    formData.value = Object.assign({}, row, {button: button});
  } else {
    formData.value = {button: button};
  }

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const resetToken = () => {
  formData.value.appKey = tool.uuid36();
  formData.value.appSecret = tool.uuid36();
};

const submitForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true;
        api.post(formData.value.button.dataDestUrl, formData.value).then(res => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          dataTable.value.findPage();
          editLoading.value = false;
        }).catch(() => {
          editLoading.value = false;
        })
      }).catch(() => {});
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  })
};
</script>